/*
 * GeoVISTA Center (Penn State, Dept. of Geography)
 * Copyright (c), 2003-2011,  Jin Chen and Alan M. MacEachren, GeoVISTA Center, Penn State University
 * All Rights Researved.
 *
 * This library is developed and distributed for free usage,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * You can redistribute and/or modify it under the terms of the
 * Simplified BSD License
 *
 *
 *
 *
 *
 *
 *
 *
 * @author: jin Chen 
 * @date: Sep 24, 2003$
 * @version: 1.0
 */
package edu.psu.geovista.app.pcp.toolkits;

import java.io.File;
import java.io.FileNotFoundException;

public class PcpToolkits {
    /**
      * find the  first found file with extension as <ext> and with name contain <key>
      * @param dir   dir under which search is going on
      * @param key
      * @param ext   extension exclude "."
      */
     public static File findFileByName(File dir,String key, String ext) throws FileNotFoundException {
        if(dir==null||key==null||ext==null){
            throw new NullPointerException("Unable to handle null data");
        }
        if(!dir.exists() ){
            throw new FileNotFoundException("Unable to find file:"+dir.getName() );

        }
        File[] files=dir.listFiles();
        if(files==null||files.length ==0)return null;

        for (int i=0;i<files.length ;i++){
            if(getFileExtension(files[i]).equalsIgnoreCase(ext) ){
                String fileName=files[i].getName() ;
                if(fileName.indexOf(key)>=0){
                    //found
                    return files[i];
                }
            }
        }
        return null;
     }

     public static String getFileExtension(File file) {
         if(file.isDirectory() )return null;
         String fn=file.getName() ;
         int indexOfDot=fn.lastIndexOf(".");
         String ext=fn.substring(indexOfDot+1);
         return ext;
     }
}
